import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { InMemoryCache } from 'apollo-cache-inmemory'
import fetch from './fetch'

const httpLink = new HttpLink({
  // You should use an absolute URL here
  uri: process.env.GRAPHQL_SERVER,
  credentials: 'same-origin',
  fetch
})

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = wx.getStorageSync('token')
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      Authorization: token ? `Bearer ${token}` : ''
    }
  }
})

// Create the apollo client
const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
  connectToDevTools: true
})

apolloClient.queryLoading = (query, successFn, errorFn) => {
  wx.showLoading()
  apolloClient
    .query(query)
    .then(result => {
      successFn && successFn(result)
      wx.hideLoading()
    })
    .catch(error => {
      errorFn && errorFn(error)
      wx.hideLoading()
    })
}

apolloClient.mutateLoading = (mutation, successFn, errorFn) => {
  wx.showLoading()
  apolloClient
    .mutate(mutation)
    .then(result => {
      successFn && successFn(result)
      wx.hideLoading()
    })
    .catch(error => {
      errorFn && errorFn(error)
      wx.hideLoading()
    })
}

export default apolloClient
